package org.oschina.api.discuss.forum.service;

import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.discuss.forum.dao.DiscussForumDAO;
import org.oschina.api.discuss.forum.model.DiscussForum;
import org.oschina.api.discuss.forum.vo.DiscussForumVo;
import org.oschina.api.index.service.IndexService;
import org.oschina.bean.Result;
import org.oschina.security.ISecurity;
import org.oschina.security.annotation.Require;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DiscussForumService extends BaseService {

	@Autowired
	private DiscussForumDAO discussForumDAO;
	@Autowired
	private IndexService indexService;
	@Autowired
	private ISecurity security;
	
	/**
	 * 返回
	 * @return
	 */
	public List<DiscussForumVo> findVo()
	{
		List<DiscussForumVo> result=_findVo();
		if(!security.require(new String[]{Module.MODULE_15}, getToken(), false))
		{
			for(DiscussForumVo discussForumVo:result)
			{
				discussForumVo.setCheck(null);
				discussForumVo.setIndex(null);
				discussForumVo.setIndex_type(null);
				discussForumVo.setCreate_time(null);
			}
		}
		return result;
	}
	
	/**
	 * 创建
	 * @param discussForum
	 * @return
	 */
	@Require(authorization=Module.MODULE_15)
	public Result create(DiscussForum discussForum)
	{
		return ResultUtil.getSuccess(_create(discussForum));
	}
	
	/**
	 * 更新
	 * @param discussForum
	 * @return
	 */
	@Require(authorization=Module.MODULE_15)
	public Result update(DiscussForum discussForum)
	{
		if(_update(discussForum)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(discussForum);
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public DiscussForumVo _findVoById(int id)
	{
		return discussForumDAO.findVoById(id);
	}
	
	/**
	 * 更新
	 * @param discussForum
	 * @return
	 */
	private int _update(DiscussForum discussForum)
	{
		return discussForumDAO.update(discussForum);
	}
	
	/**
	 * 创建
	 * @param discussForum
	 * @return
	 */
	private DiscussForum _create(DiscussForum discussForum)
	{
		discussForum.setId(_getIndex());
		discussForum.setCreate_time(DateUtil.now());
		return discussForumDAO.create(discussForum);
	}
	
	/**
	 * 根据首页类型返回
	 * @param type
	 * @return
	 */
	public List<DiscussForumVo> _findByIndexType(int type)
	{
		return discussForumDAO.findByIndexType(type);
	}
	
	/**
	 * 返回
	 * @return
	 */
	private List<DiscussForumVo> _findVo()
	{
		return discussForumDAO.findVo();
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_DISCUSS_FORUM);
	}
}
